import React, {
    useState
} from "react";
import $ from "jquery";

function MyUpload(props){
    const [uploadPercent, setUploadPercent] = useState(0);
    const [uploadSign, setUploadSign] = useState(1);
    //监听文件上传进度，实时更新变量uploadPercent进行显示
    const resultProgress = (e) => {
        let percent = e.loaded / e.total * 100;
        setUploadPercent(percent);
    }
    const uploadMethod = () => {
        let file = document.getElementById("file").files[0];
        let formData = new FormData();
        formData.append("file", file);
        let sysInfo = JSON.parse(sessionStorage.getItem("sysInfo"));
        let webAddr = sysInfo["E47"];
        $.ajax({
            url: webAddr + "/bumf/upload",
            type: "post",
            data: formData,
            async: true,
            dataType:'json',
            headers: {
                Authorization: sessionStorage.getItem("token")
            },
            cache: false, // 上传文件无需缓存
            processData : false, // 使数据不做处理
            contentType: false, //不额外设置请求头
            xhr: function () {
                //获取ajax中的ajaxSettings的xhr对象  为他的upload属性绑定progress事件的处理函数
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    //检查其属性upload是否存在
                    myXhr.upload.addEventListener("progress", resultProgress, false);
                }
                return myXhr;
            },
            success: function (data) {
                setUploadSign(1);
            },
            error: function (data) {
                setUploadSign(0);
            }
        })
    }
    return (
        <div className="my_upload_container">
            <input type="file" id="file" name="file "/>
            {
                uploadSign === 1?
                <span>{uploadPercent}%</span>:
                <span style={{color: "#ff0000"}}>上传失败！</span>
            }
            <div className="upload_btn" onClick={uploadMethod}>确认上传</div>
        </div>
    )
}

export default MyUpload;